#!/usr/bin/env node

const execa = require('execa')
const chalk = require('chalk')

const run = async () => {
  let branch = ''
  let result = ''

  try {
    console.log(chalk.gray(`获取当前分支...`))
    const { stdout } = await execa.command('git symbolic-ref --short -q HEAD')

    branch = stdout
    console.log(chalk.gray(`当前分支为: ${branch}`))
  } catch (error) {
    console.log(chalk.red(`获取分支失败：${error.message}`))
    process.exit(1) // 以失败码退出，用于 git hooks 拦截识别
  }

  try {
    console.log(chalk.gray(`检查当前分支是否推送过远程仓库...`))
    await execa.command(`git rev-parse --abbrev-ref ${branch}@{upstream}`)
    console.log(chalk.gray(`当前分支存在于 ${branch} 远程仓库...`))
  } catch (error) {
    console.log(
      chalk.yellow(`当前分支 ${branch} 未推送远程仓库 ${error.message}`),
    )

    try {
      console.log(chalk.green(`尝试推送分支 ${branch} 至远程仓库`))
      const { stderr } = await execa.command(
        `git push --set-upstream origin ${branch} --no-verify`,
      )

      result = stderr
    } catch (error) {
      console.log(chalk.red(`提交 gerrit 失败：${error.message}`))
      process.exit(1)
    }
  }

  try {
    console.log(chalk.gray(`对分支 ${branch} 提交 gerrit ...`))
    const { stderr } = await execa.command(
      `git push origin HEAD:refs/for/${branch} --no-verify`,
    )

    result = stderr
  } catch (error) {
    console.log(chalk.red(`提交 gerrit 失败：${error.message}`))
    process.exit(1)
  }

  console.log(chalk.green(`${branch} 提交 gerrit 成功，信息如下：\n${result}`))

  process.exit(0) // 以成功码退出，用于 git hooks 通过识别
}

run()